﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ByteSite.Common;

namespace ByteSite.Web.admin.form
{
    public partial class form_edit : Web.UI.ManagePage
    {
        private string action = DTEnums.ActionEnum.Add.ToString();//操作类型
        private int id = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            string _action = DTRequest.GetQueryString("action");

            if (!string.IsNullOrEmpty(_action) && _action == DTEnums.ActionEnum.Edit.ToString())
            {
                this.action = DTEnums.ActionEnum.Edit.ToString();//修改类型
                this.id = DTRequest.GetQueryInt("id");
                if (this.id == 0)
                {
                    JscriptMsg("传输参数不正确！", "back");
                    return;
                }
                if (!new BLL.forms().Exists(this.id))
                {
                    JscriptMsg("记录不存在或已删除！", "back");
                    return;
                }
            }
            if (!Page.IsPostBack)
            {
                ChkAdminLevel("form_list", DTEnums.ActionEnum.View.ToString()); //检查权限
                SiteBind(); //绑定站点
                FieldBind(); //绑定扩展字段
                if (action == DTEnums.ActionEnum.Edit.ToString()) //修改
                {
                    ShowInfo(this.id);
                }
                else
                {
                    //txtName.Attributes.Add("ajaxurl", "../../tools/admin_ajax.ashx?action=channel_name_validate");
                }
            }
        }

        #region 绑定站点=================================
        private void SiteBind()
        {
            BLL.sites bll = new BLL.sites();
            List<Entitys.dt_sites> list = bll.GetList(0, x => x.is_lock == 0, x => x.sort_id);

            this.ddlSiteId.Items.Clear();
            this.ddlSiteId.Items.Add(new ListItem("所有站点", ""));
            foreach (Entitys.dt_sites model in list)
            {
                this.ddlSiteId.Items.Add(new ListItem(model.title.ToString(), model.id.ToString()));
            }
        }
        #endregion

        #region 绑定扩展字段=============================
        private void FieldBind()
        {
            BLL.form_attribute_field bll = new BLL.form_attribute_field();
            List<Entitys.dt_form_attribute_field> list = bll.GetList(0, x => true, "is_sys desc,sort_id asc,id desc");

            this.cblAttributeField.Items.Clear();
            this.cblShowAttributeField.Items.Clear();
            foreach (Entitys.dt_form_attribute_field model in list)
            {
                this.cblAttributeField.Items.Add(new ListItem(model.title.ToString(), model.name.ToString() + "," + model.id.ToString()));
                this.cblShowAttributeField.Items.Add(new ListItem(model.title.ToString(), model.name.ToString() + "," + model.id.ToString()));
            }
        }
        #endregion

        #region 赋值操作=================================
        private void ShowInfo(int _id)
        {
            BLL.forms bll = new BLL.forms();
            Entitys.dt_forms model = bll.GetModel(_id);

            txtTitle.Text = model.title;
            txtName.Text = model.name;
            txtName.Focus(); //设置焦点，防止JS无法提交
            //txtName.Attributes.Add("ajaxurl", "../../tools/admin_ajax.ashx?action=channel_name_validate&old_channel_name=" + Utils.UrlEncode(model.name));
            ddlSiteId.SelectedValue = model.site_id.ToString();
            if (model.is_lock == 1)
            {
                cbIsLock.Checked = false;
            }
            txtSortId.Text = model.sort_id.ToString();

            //赋值扩展字段
            if (model.form_fields != null)
            {
                for (int i = 0; i < cblAttributeField.Items.Count; i++)
                {
                    string[] fieldIdArr = cblAttributeField.Items[i].Value.Split(',');//分解出ID值
                    Entitys.dt_form_field modelt = model.form_fields.Find(p => p.field_id == int.Parse(fieldIdArr[1]));//查找对应的字段ID
                    if (modelt != null)
                    {
                        cblAttributeField.Items[i].Selected = true;
                    }
                }
            }

            if (model.show_form_fields != null)
            {
                for (int i = 0; i < cblShowAttributeField.Items.Count; i++)
                {
                    string[] fieldIdArr = cblShowAttributeField.Items[i].Value.Split(',');//分解出ID值
                    Entitys.dt_form_show_column modelt = model.show_form_fields.Find(p => p.field_id == int.Parse(fieldIdArr[1]));//查找对应的字段ID
                    if (modelt != null)
                    {
                        cblShowAttributeField.Items[i].Selected = true;
                    }
                }
            }

        }
        #endregion

        #region 增加操作=================================
        private bool DoAdd()
        {
            Entitys.dt_forms model = new Entitys.dt_forms();
            BLL.forms bll = new BLL.forms();

            model.site_id = Utils.StrToInt(ddlSiteId.SelectedValue, 0);
            model.name = txtName.Text.Trim();
            model.title = txtTitle.Text.Trim();

            model.add_time = DateTime.Now;
            model.add_user = GetAdminInfo().id;
            if (cbIsLock.Checked == false)
            {
                model.is_lock = 1;
            }
            model.sort_id = Utils.StrToInt(txtSortId.Text.Trim(), 99);

            //添加频道扩展字段
            List<Entitys.dt_form_field> ls = new List<Entitys.dt_form_field>();
            for (int i = 0; i < cblAttributeField.Items.Count; i++)
            {
                if (cblAttributeField.Items[i].Selected)
                {
                    string[] fieldIdArr = cblAttributeField.Items[i].Value.Split(','); //分解出ID值
                    ls.Add(new Entitys.dt_form_field { field_id = Utils.StrToInt(fieldIdArr[1], 0)});
                }
            }
            model.form_fields = ls;

            List<Entitys.dt_form_show_column> showls = new List<Entitys.dt_form_show_column>();
            for (int i = 0; i < cblShowAttributeField.Items.Count; i++)
            {
                if (cblShowAttributeField.Items[i].Selected)
                {
                    string[] fieldIdArr = cblShowAttributeField.Items[i].Value.Split(','); //分解出ID值
                    showls.Add(new Entitys.dt_form_show_column { field_id = Utils.StrToInt(fieldIdArr[1], 0) });
                }
            }
            model.show_form_fields = showls;

            if (bll.Add(model) < 1)
            {
                return false;
            }

            AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加表单" + model.title); //记录日志
            return true;
        }
        #endregion

        #region 修改操作=================================
        private bool DoEdit(int _id)
        {
            BLL.forms bll = new BLL.forms();
            Entitys.dt_forms model = bll.GetModel(_id);

            string old_name = model.name;
            model.site_id = Utils.StrToInt(ddlSiteId.SelectedValue, 0);
            model.name = txtName.Text.Trim();
            model.title = txtTitle.Text.Trim();
            model.is_lock = 0;
            if (cbIsLock.Checked == false)
            {
                model.is_lock = 1;
            }
            model.sort_id = Utils.StrToInt(txtSortId.Text.Trim(), 99); 
            model.update_time = DateTime.Now;
            model.update_user = GetAdminInfo().id;

            //添加频道扩展字段
            List<Entitys.dt_form_field> ls = new List<Entitys.dt_form_field>();
            for (int i = 0; i < cblAttributeField.Items.Count; i++)
            {
                if (cblAttributeField.Items[i].Selected)
                {
                    string[] fieldIdArr = cblAttributeField.Items[i].Value.Split(','); //分解出ID值
                    ls.Add(new Entitys.dt_form_field { form_id = model.id, field_id = Utils.StrToInt(fieldIdArr[1], 0) });
                }
            }
            model.form_fields = ls;

            List<Entitys.dt_form_show_column> showls = new List<Entitys.dt_form_show_column>();
            for (int i = 0; i < cblShowAttributeField.Items.Count; i++)
            {
                if (cblShowAttributeField.Items[i].Selected)
                {
                    string[] fieldIdArr = cblShowAttributeField.Items[i].Value.Split(','); //分解出ID值
                    showls.Add(new Entitys.dt_form_show_column { field_id = Utils.StrToInt(fieldIdArr[1], 0) });
                }
            }
            model.show_form_fields = showls;

            if (!bll.Update(model))
            {
                return false;
            }

            AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改表单" + model.title); //记录日志
            return true;
        }
        #endregion

        //保存
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("form_list", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                if (!DoEdit(this.id))
                {
                    JscriptMsg("保存过程中发生错误！", "");
                    return;
                }
                JscriptMsg("修改频道成功！", "form_list.aspx", "parent.loadMenuTree");
            }
            else //添加
            {
                ChkAdminLevel("form_list", DTEnums.ActionEnum.Add.ToString()); //检查权限
                if (!DoAdd())
                {
                    JscriptMsg("保存过程中发生错误！", "");
                    return;
                }
                JscriptMsg("添加频道成功！", "form_list.aspx", "parent.loadMenuTree");
            }
            CacheHelper.Remove(DTKeys.CACHE_SITE_CHANNEL_LIST); //更新一下频道的缓存
        }

    }
}